package com.mineoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mineoj.annotation.AuthCheck;
import com.mineoj.common.BaseResponse;
import com.mineoj.common.DeleteRequest;
import com.mineoj.common.ErrorCode;
import com.mineoj.common.ResultUtils;
import com.mineoj.constant.UserConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.exception.ThrowUtils;
import com.mineoj.model.dto.news.NewsAddRequest;
import com.mineoj.model.dto.news.NewsEditRequest;
import com.mineoj.model.dto.news.NewsQueryRequest;
import com.mineoj.model.entity.News;
import com.mineoj.model.entity.User;
import com.mineoj.model.vo.NewsVO;
import com.mineoj.service.NewsService;
import com.mineoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 新鲜事接口
 *
 
 */
@RestController
@RequestMapping("/news")
@Slf4j
public class NewsController {

    @Resource
    private NewsService newsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param newsAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addNews(@RequestBody NewsAddRequest newsAddRequest, HttpServletRequest request) {
        if (newsAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        News news = new News();
        BeanUtils.copyProperties(newsAddRequest, news);
        newsService.validNews(news, true);

        // 登录才能提交新鲜事
        final User loginUser = userService.getLoginUser(request);
        news.setUserId(loginUser.getId());
        news.setThumbNum(0);
        news.setCommentNum(0);
        boolean result = newsService.save(news);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newsId = news.getId();

        return ResultUtils.success(newsId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteNews(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        News oldNews = newsService.getById(id);
        ThrowUtils.throwIf(oldNews == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldNews.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = newsService.deleteById(id);
        return ResultUtils.success(b);
    }
    

    /**
     * 根据 id 获取
     *
     * @param id
     * @return NewsVO
     */
    @GetMapping("/get/vo")
    public BaseResponse<NewsVO> getNewsVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        News news = newsService.getById(id);
        if (news == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(newsService.getNewsVO(news, request));
    }

    /**
     * 分页获取新鲜事列表
     *
     * @param newsQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<News>> listNewsByPage(@RequestBody NewsQueryRequest newsQueryRequest,
                                                           HttpServletRequest request) {
        long current = newsQueryRequest.getCurrent();
        long size = newsQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<News> newsPage = newsService.page(new Page<>(current, size),
                newsService.getQueryWrapper(newsQueryRequest));
        return ResultUtils.success(newsPage);
    }
    

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param newsQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<NewsVO>> listMyNewsByPage(@RequestBody NewsQueryRequest newsQueryRequest,
            HttpServletRequest request) {
        if (newsQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        newsQueryRequest.setUserId(loginUser.getId());
        long current = newsQueryRequest.getCurrent();
        long size = newsQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<News> newsPage = newsService.page(new Page<>(current, size),
                newsService.getQueryWrapper(newsQueryRequest));
        return ResultUtils.success(newsService.getNewsVOPage(newsPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param newsEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editNews(@RequestBody NewsEditRequest newsEditRequest, HttpServletRequest request) {
        if (newsEditRequest == null || newsEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        News news = new News();
        BeanUtils.copyProperties(newsEditRequest, news);

        // 参数校验
        newsService.validNews(news, false);
        User loginUser = userService.getLoginUser(request);
        long id = newsEditRequest.getId();
        // 判断是否存在
        News oldNews = newsService.getById(id);
        ThrowUtils.throwIf(oldNews == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldNews.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = newsService.updateById(news);
        return ResultUtils.success(result);
    }

}
